package com.lwj.springbootvue.config;


import com.lwj.springbootvue.filter.JwtAuthticationFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Collections;

@Configuration
@EnableWebSecurity // 开启WebSecurity
public class securityConfig {

    private final authenticationDetailsService detailsService; // 自定义的验证方式
    private final JwtAuthticationFilter jwtAuthticationFilter;// jwt 过滤链

    public securityConfig(authenticationDetailsService detailsService, JwtAuthticationFilter jwtAuthticationFilter) {
        this.detailsService = detailsService;
        this.jwtAuthticationFilter = jwtAuthticationFilter;
    }

    // 配置密码编码器(密码加密方式)
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    // 创建AuthenticationManager,登录时需要执行一次Authenticate 验证
    @Bean
    public AuthenticationManager sysUserAuthenticationManager() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setPasswordEncoder(passwordEncoder());
        provider.setUserDetailsService(detailsService);
        return new ProviderManager(provider);
    }

    /**
        对于路径匹配/user/login的请求，允许所有用户访问，无论他们是否认证。
        对于所有其他的请求，要求用户必须认证才能访问。
    **/
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 配置关闭csrf
        http.csrf(csrf->csrf.disable());
        // 配置拦截方式
        // permitAll 随意访问
        http.authorizeHttpRequests(auth->// "/user/login","/user/register","/user/test"
                auth.requestMatchers("/user/login","/user/register","/user/test").permitAll() // 不拦截
                .anyRequest().authenticated() // 其他所有请求需要认证
        );
        // 开启form认证
        http.formLogin(Customizer.withDefaults());
        // 配置跨域
        http.cors(cors -> cors.configurationSource(configurationSource()));
        // 配置过滤链接
            // 将token 过滤链  放在最前面
        http.addFilterBefore(jwtAuthticationFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }


    // 配置跨域，允许跨域 配置CorsConfigurationSource
    public CorsConfigurationSource configurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedMethods(Collections.singletonList("*"));
        corsConfiguration.setAllowedHeaders(Collections.singletonList("*"));
        corsConfiguration.setAllowedOrigins(Collections.singletonList("*"));

        // 创建 CorsConfigurationSource对象
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",corsConfiguration);
        return source;
    }




}
